<?php
require_once('Model/SiteManage.php');
require_once('Model/DB.php');
require_once('Model/Validate.php');
class Model_Seo
{
    var $sys;
    var $config;
    
    public function __construct()
    {
        $this->sys    = new Model_SiteManage();
        $config       = __get_config('plugin.ini');
        $this->config = $config['MANAGE_SEO']; 
    }
    private function getApiKey($key = 'google')
    {
        if (!empty($this->config[$key.'_key'])){
            // 詳細は複数キー対応予定
            $keys = explode(',', $this->config[$key.'_key']);
            return $keys[0];
        }
        return false;
    }
    //
    public function insert($data)
    {
        $db = new Model_DB();
        return $db->insert('M_SEO', $data);
    }
    public function update($id, $data)
    {
        $db = new Model_DB();
        return $db->update($id, 'M_SEO', $data);
    }
    public function get($id)
    {
        $db = new Model_DB();
        $sql = sprintf("select * from M_SEO where id = " . $db->escape($id) . " and enabled = 1");
        $db->query($sql);
        return $db->fetch();
    }
    public function getListCount($data)
    {
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        $sql   = "select count(*) from M_SEO";
        $sql  .= (!empty($where) ? " where ".implode(' AND ', $where) : "");
        $db->query($sql);
        if ($db->res){
            return array_shift($res = $db->fetch());
        }
        return false;
    }
    public function getList($data, $orderby = 'id asc', $limit = '', $offset = '')
    {//var_dump($data);exit;
        $list  = array();
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        $sql   = "select * from M_SEO";
        $sql  .= (!empty($where) ? " where ".implode(' AND ', $where) : "") . (!empty($orderby) ? " order by {$orderby}" : "") . (!empty($limit) ? " limit {$limit}" : "") . (!empty($offset) ? " offset {$offset}" : "");
        $db->query($sql);
        if ($db->res){
            while($res = $db->fetch()){
                if(isset($res['id'])){
                    $list[$res['id']] = $res;
                }
                else{
                    $list[] = $res;
                }
            }
        }
        return $list;
    }
    private function createSearchCondition($data, $prefix = '')
    {
        $db    = new Model_DB();
        $where = array();
        if ($prefix != ''){
            $prefix = $prefix . '.';
        }
        $where[] = "{$prefix}enabled = 1";
        //$where[] = "{$prefix}site_id = ". $this->sys->getCurrentSiteID();//不要？

        foreach($db->getFieldList('M_SEO') as $key => $_){
            if (isset($data[$key]) && !empty($data[$key])){
                $value = $db->escape($data[$key]);
                if ($key == 'keyword' || $key == 'url'){
                    $where[] = "{$prefix}{$key} collate utf8_unicode_ci like '%{$value}%'";
                }
            }
        }
        return $where;
    }
    
    public function validate(&$data, &$err)
    {
        $validate = new Model_Validate();
        // required
        $keys = explode(',', 'keyword,url');
        foreach($keys as $key){
            if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                $err[$key]['NotEmpty'] = true;
            }
        }
        // int
        $keys = explode(',', 'rank');
        foreach($keys as $key){
            if ($data[$key] != '' && $validate->Int($data[$key])){
                $err[$key]['Int'] = true;
            }
        }
        
        //urlチェック
        $keys = explode(',', 'url');
        foreach($keys as $key){
            if($data[$key] != '' and !preg_match("/^(https?|ftp)(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)$/", $data[$key]) ) {
                $err[$key]['Url'] = true;
            }
        }
        
        //メールアドレスチェック
        $keys = explode(',', 'email');
        
        return empty($err);
    }
    
    //
    public function getFormKeys()
    {
        $db = new Model_DB();
        return array_keys($db->getFieldList('M_SEO'));
    }
    //　状態
    public function getStatusMap()
    {
        $map    = array();
        $map[0] = '非公開';
        $map[1] = '公開';
        $map[2] = '仮登録';
        return $map;
    }
    public function getStatusName($id)
    {
        $map = $this->getStatusMap();
        return isset($map[$id]) ? $map[$id] : '';
    }
    //
    /*
     * 検索エンジン順位取得
     */
    public function getSearchRank($keyword, $url, $api = 'google')
    {
        if ($api == 'google'){
            return $this->getGoogleRank($keyword, $url);
        }
        if ($api == 'yahoo'){
            return $this->getYahooRank($keyword, $url);
        }
        return false;
    }
     private function getGoogleRank($keyword, $url)
     {
         $api_url = 'https://www.googleapis.com/customsearch/v1?key=' . $this->getApiKey('google') . '&cx=013036536707430787589:_pqjad5hr1a&cr=countryJP&lr=lang_ja&gl=jp&q=' . urlencode($keyword);
         $rank    = false;
         $start   = 1;
         while($rank == false){
             $res = json_decode(file_get_contents($api_url . '&start=' . $start));
             if (isset($res->error)){
                 return false;
             }
             foreach($res->items as $num => $item){
                 if(strpos($item->link, $url) !== false){
                     $rank = $res->queries->request[0]->startIndex + $num;
                     return $rank;
                 }
             }
             if (isset($res->queries->nextPage)){
                 $start = $res->queries->nextPage->startIndex;
                 if ($start >= 100){
                     return false;
                 }
             }
             sleep(1);    // API連続アクセスの間隔調整
         }
         return $rank;
     }
     private function getYahooRank($keyword, $url)
     {
         $api_url = 'http://search.yahooapis.jp/WebSearchServicePro/V1/webSearch?appid=' . $this->getApiKey('yahoo') . '&results=20&query=' . urlencode($keyword);
         $rank    = false;
         $start   = 1;
         while($rank == false){
             $res = simplexml_load_file($api_url . '&start=' . $start);
             if (!$res){
                 return false;
             }
             $num = 0;
             foreach($res->Result as $item){
                 if(strpos($item->Url, $url) !== false){
                     $rank = $start + $num;
                     return $rank;
                 }
                 $num++;
             }
             $start = $start + $res->attributes()->totalResultsReturned;
             if ($start >= 100){
                 return false;
             }
             sleep(1);    // API連続アクセスの間隔調整
         }
         return $rank;
     }
}
?>